<template>
	<view class="loading-container">
		<view class="bg">
			<!-- <image src="/static/loading-bg.png" mode="aspectFit"></image> -->
		</view>
		<view class="footer">
			<!-- <image src="/static/lvgang.png" mode="aspectFit"></image> -->
			<!-- <text style="margin-bottom: 10rpx;">江苏绿港现代农业发展股份有限公司</text> -->
			<up-loading-icon color="#43C679" :size="28"></up-loading-icon>
		</view>

		<!-- 更新 -->
		<!-- #ifdef APP-PLUS -->
		<upVersion :upLoadUrl="upLoadUrl" :newVision="newVision" :appStoreUrl='appStoreUrl' :show="show" :log="log"
			:is_enforce="is_enforce" @close="close"></upVersion>
		<!-- #endif -->

		<!-- #ifdef H5 -->
		<hwUpVersion :newVision="hwnewVision" :show="hwshow" :log="hwlog"></hwUpVersion>
		<!-- #endif -->
	</view>
</template>

<script>
	import {
		showFloatingNotificationPopup
	} from '@/utils/notify.js';
	import upVersion from "@/components/as-upVersion/as-upVersion.vue";
	import hwUpVersion from "@/components/as-upVersion/hw-upVersion.vue";
	import {
		useUserStore
	} from '@/pinia-store/user';
	import {
		useLoginStore,
		useStartTodoPolling
	} from "@/pinia-store/user.js";
	import {
		COMMON_API_BASE_URL
	} from '@/utils/request.js';
	import {
		ChatSql
	} from '@/utils/sql/chat.js';
	import {
		SysUser
	} from '@/utils/sql/user.js';
	import {
		compareVersions
	} from '@/utils/tools.js';

	export default {
		name: 'loading',
		components: {
			upVersion,
			hwUpVersion
		},
		data() {
			return {
				// 更新参数
				newVision: 0, //版本号
				upLoadUrl: '', //下载地址
				appStoreUrl: '', //下载地址
				log: '', //备注
				show: false, // 展示更新
        is_enforce: 0, // 是否强制更新
				hwnewVision: 0, // h5版本号
				hwlog: '', //备注
				hwshow: false, // h5展示更新
			}
		},
		created() {
			if (uni.getSystemInfoSync().uniPlatform == 'web') {
				if (!uni.getStorageSync('token') && !uni.getStorageSync('user')) {
					this.redirect("/pages/user/login");
				} else {
					// this.redirect("/pages/chat/list/index");
					this.redirect("/pages/workspace/home/index");
				}
			}

			// 判断有没有存储权限
			// #ifdef APP-PLUS

			var _this = this
			plus.android.requestPermissions(['android.permission.WRITE_EXTERNAL_STORAGE'], function(e) {
				if (e.deniedAlways.length > 0) { //权限被永久拒绝
					// 弹出提示框解释为何需要读写手机储存权限，引导用户打开设置页面开启
					uni.showModal({
						title: '存储权限',
						content: '您拒绝了存储权限，请去设置-应用开启存储权限。',
						success: function(res) {
							if (res.confirm) {
								// 用户点击确定 执行登录流程
							} else if (res.cancel) {
								// 用户点击取消 提示必须授权
							}
						}
					});
				}
				if (e.deniedPresent.length > 0) { //权限被临时拒绝
					// 弹出提示框解释为何需要读写手机储存权限，可再次调用plus.android.requestPermissions申请权限
					plus.android.requestPermissions(['android.permission.WRITE_EXTERNAL_STORAGE'])
				}
				if (e.granted.length > 0) { //权限被允许
					// 调用依赖获取读写手机储存权限的代码
					// 获取权限成功之后调用的函数

					// 获取登录信息
					SysUser.init().then(init => {
						// 创建聊天相关
						ChatSql.createChatTable();

						if (init.length === 0) {
							console.log('无登录信息');
							_this.redirect("/pages/user/login");
						} else {
							// 用户信息写入缓存
							const userStore = useUserStore();
							userStore.setUser(init[0]);
							// token
							const loginStore = useLoginStore();
							loginStore.login(init[0].token);
							uni.$emit('initJpush', init[0].phone)
							// _this.redirect("/pages/chat/list/index");
							_this.redirect("/pages/workspace/home/index");
						}
					}).catch(initErr => {
						console.log('初始化SQlite失败', initErr);
						_this.redirect("/pages/user/login");
					})
				}
			}, function(e) {
				// console.log('R12133313221' + JSON.stringify(e));
			});
			// #endif
			this.Timingmarkers()
		},
		methods: {
			/**
			 * 获取版本
			 */
			checkVersion(callback) {
				var info = uni.getSystemInfoSync();
				uni.request({
					url: `${COMMON_API_BASE_URL}/dist/interface/public/index.php/index/Index/get_new_version`, //仅为示例，并非真实接口地址。
					header: {
						'content-type': 'application/json'
					},
					method: 'POST',
					dataType: 'json',
					success: (res) => {
						//回调赋值
						if (res.data.data.code === 0) {
							return;
						}

						let version
						// #ifdef H5
						version = uni.getStorageSync('localVersion') || info?.appVersion
						// #endif

						// #ifdef APP-PLUS
						version = info.appWgtVersion
						// #endif

						if (compareVersions(version, res.data.data.version_no) === -1) {
							// #ifdef APP-PLUS
							this.newVision = res.data.data.version_no
							this.upLoadUrl = "https://cloud.mfarmers.com" + res.data.data.url
							this.log = res.data.data.remark
							this.show = true
              this.is_enforce = res.data.data.is_enforce
							// #endif

							// #ifdef H5
							this.hwnewVision = res.data.data.version_no
							this.hwlog = res.data.data.remark
							this.hwshow = true
							// #endif
						} else {
							callback();
						}
					},
					fail() {
						callback();
					}
				});
			},
			redirect(url) {
				// #ifdef APP
				this.checkVersion(() => {
					setTimeout(() => {
						uni.reLaunch({
							url: url
						})
					}, 1000)
				});
				// #endif

				// #ifdef H5
				setTimeout(() => {
					showFloatingNotificationPopup();
					uni.reLaunch({
						url: url
					})
				}, 1000)
				// #endif
			},
			Timingmarkers() {
				const pollingStore = useStartTodoPolling();
				pollingStore.start();
			},
			close() {
				this.show = false;
				setTimeout(() => {
					uni.reLaunch({
						url: "/pages/workspace/home/index"
					})
				}, 500)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.loading-container {
		background-image: url('@/static/loading-copy.jpg');
		background-size: cover;
		background-position: center;
		background-repeat: no-repeat;
		will-change: transform;
		backface-visibility: hidden;
		user-select: none;
		-webkit-touch-callout: none;
		overflow: hidden;
		position: relative;
		width: 100vw;

		background-color: #fff;
		//#ifdef APP-PLUS
		height: 100vh;
		// #endif

		// #ifdef H5
		height: 91vh;

		// #endif
		.bg {
			margin-top: 220rpx;
			display: flex;
			justify-content: center;

			image {
				height: 720rpx;
			}
		}

		.footer {
			position: fixed;
			width: 100%;

			//#ifdef APP-PLUS
			bottom: 50rpx;
			// #endif

			// #ifdef H5
			bottom: 0rpx;
			// #endif
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;

			image {
				height: 80rpx;
				margin-bottom: 18rpx;
			}
		}
	}
</style>